<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter='20'>
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear='getUserList'>
            <el-button @click='getUserList' slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click='addVserDialogVisble=true'>添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table border stripe :data='userList'>
        <el-table-column label='操作'>
          <template slot-scope='scope'>
            <el-button type="primary" size="mini" icon='el-icon-edit' @click='showEditDialog(scope.row.id)'></el-button>
            <el-button type="danger" size="mini" icon='el-icon-delete' @click='removeEditDialog(scope.row.id)'>
            </el-button>
            <el-tooltip effect='dark' content='分配角色' placement='top' :enterable='false'>
              <el-button type="warning" size="mini" icon='el-icon-setting' @click='setRoles(scope.row)'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <TableList :col='column' />
        <el-table-column label='状态' prop='mg_state'>
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[2, 4, 6,8]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 对话框 -->
    <el-dialog title="添加用户" :visible.sync='addVserDialogVisble'>
      <el-form :model="addDialogForm" :rules="addDialogRulesForm" ref="addDialogRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addDialogForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addDialogForm.password" type='password'></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addDialogForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addDialogForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button class="quxiao" @click="canelFrom">取消</el-button>
        <el-button type="primary" @click="addForm">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" :rules="editDialogRulesForm" ref="editDialogRef">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button class="quxiao" @click="editDialogClose">取消</el-button>
        <el-button type="primary" @click="editAddDialog">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="setRolesDialogVisible" width="50%">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <el-select placeholder="请选择" v-model="selectedRoled">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>

      </div>
      <span slot="footer">
        <el-button @click="saveRoleClose" class="quxiao">Cancel</el-button>
        <el-button type="primary" @click="saveUserInfo">OK</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script scoped>
import { userListAPI, usersStateAPI, rolesAPI, addUserAPI, editUserAPI, UserRemoveAPI, editUserInfoAPI, saveRolesAPI } from '@/api/user'
import TableList from '@/components/table.vue'
export default {
  // 组件名称
  name: 'demo',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: { TableList },
  // 组件状态值
  data () {
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机'))
    }
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    return {
      selectedRoled: '',
      roleList: [],
      userInfo: {},
      setRolesDialogVisible: false,
      // 编辑对象
      editForm: {},
      // 编辑校验规则
      editDialogRulesForm: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, tigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, tigger: 'blur' }
        ]
      },
      // 显示提示框显示与隐藏
      editDialogVisible: false,
      // 对话框内容
      addDialogForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 控制对话框显示和隐藏
      addVserDialogVisble: false,
      // 对话框校验规则
      addDialogRulesForm: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 16, message: '密码长度在 5 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, tigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, tigger: 'blur' }
        ]
      },
      column: [
        {
          name: '姓名',
          type: 'username'
        },
        {
          name: '邮箱',
          type: 'email'
        },
        {
          name: '电话',
          type: 'mobile'
        },
        {
          name: '角色',
          type: 'role_name'
        }
      ],
      userList: [],
      queryInfo: {
        query: '', // 查询参数
        pagenum: 1, // 页码
        pagesize: 2 // 每页显示条数
      },
      total: 0// 总数据
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    saveRoleClose () {
      this.selectedRoled = ''
      this.userInfo = {}
      this.addVserDialogVisble = false
    },
    async saveUserInfo () {
      await saveRolesAPI(this.userInfo.id, { rid: this.selectedRoled })
      this.$message({
        message: '更新成功',
        type: 'success'
      })
      this.getUserList()
      this.setRolesDialogVisible = false
    },
    async setRoles (row) {
      this.userInfo = row
      const { data: res } = await rolesAPI()
      this.roleList = res.data
      this.setRolesDialogVisible = true
    },
    // 删除
    async removeEditDialog (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.message.info('已取消删除')
      }
      const { data: res } = await UserRemoveAPI(id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message({
        message: '删除用户成功',
        type: 'success'
      })
      this.getUserList()
    },
    // 确认编辑
    editAddDialog () {
      this.$refs.editDialogRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await editUserInfoAPI(this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
        if (res.meta.status !== 200) return this.$message.error('更新用户失败！')
        this.getUserList()
        this.editDialogVisible = false
        this.$message({
          message: '更新用户成功！',
          type: 'success'
        })
      })
    },
    // 取消编辑
    editDialogClose () {
      this.$refs.editDialogRef.resetFields()
      this.editDialogVisible = false
    },
    // 编辑按钮
    async showEditDialog (id) {
      const { data: res } = await editUserAPI(id)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    canelFrom () {
      this.$refs.addDialogRef.resetField()
      this.addVserDialogVisble = false
    },
    // 提交表单
    addForm () {
      this.$refs.addDialogRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await addUserAPI(this.addDialogForm)
        if (res.meta.status !== 201) {
          return this.$message({
            message: '添加用户失败！',
            type: 'danger'
          })
        }
        this.$message({
          message: '添加用户成功！',
          type: 'success'
        })
        this.getUserList()
        this.canelFrom()
      })
    },
    // switch状态改变
    async userStateChanged (row) {
      const { data: res } = await usersStateAPI(row.id, row.mg_state)
      if (res.meta.status !== 200) return this.$message.error('更新用户状态失败！')
      this.$message.success('更新用户状态成功！')
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 渲染列表数据
    async getUserList () {
      const { data: res } = await userListAPI(this.queryInfo)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.total = res.data.total
      this.userList = res.data.users
    }
  },
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
  */
  created () {
    this.getUserList()
  },
  /**
  * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
  */
  mounted () {
  }
}
</script>

<style scoped>
.quxiao {
  margin-right: 20px;
}
</style>
